'use strict';
Object.defineProperty(exports, '__esModule', { value: !0 });
var __assign = function () {
  return (__assign =
    Object.assign ||
    function (e) {
      for (var n, t = 1, r = arguments.length; t < r; t++)
        for (var i in (n = arguments[t]))
          Object.prototype.hasOwnProperty.call(n, i) && (e[i] = n[i]);
      return e;
    }).apply(this, arguments);
};
function __awaiter(e, n, t, r) {
  return new (t || (t = Promise))(function (i, a) {
    function o(e) {
      try {
        c(r.next(e));
      } catch (e) {
        a(e);
      }
    }
    function s(e) {
      try {
        c(r.throw(e));
      } catch (e) {
        a(e);
      }
    }
    function c(e) {
      e.done
        ? i(e.value)
        : new t(function (n) {
            n(e.value);
          }).then(o, s);
    }
    c((r = r.apply(e, n || [])).next());
  });
}
function __generator(e, n) {
  var t,
    r,
    i,
    a,
    o = {
      label: 0,
      sent: function () {
        if (1 & i[0]) throw i[1];
        return i[1];
      },
      trys: [],
      ops: [],
    };
  return (
    (a = { next: s(0), throw: s(1), return: s(2) }),
    'function' == typeof Symbol &&
      (a[Symbol.iterator] = function () {
        return this;
      }),
    a
  );
  function s(a) {
    return function (s) {
      return (function (a) {
        if (t) throw new TypeError('Generator is already executing.');
        for (; o; )
          try {
            if (
              ((t = 1),
              r &&
                (i =
                  2 & a[0]
                    ? r.return
                    : a[0]
                    ? r.throw || ((i = r.return) && i.call(r), 0)
                    : r.next) &&
                !(i = i.call(r, a[1])).done)
            )
              return i;
            switch (((r = 0), i && (a = [2 & a[0], i.value]), a[0])) {
              case 0:
              case 1:
                i = a;
                break;
              case 4:
                return o.label++, { value: a[1], done: !1 };
              case 5:
                o.label++, (r = a[1]), (a = [0]);
                continue;
              case 7:
                (a = o.ops.pop()), o.trys.pop();
                continue;
              default:
                if (
                  !(i = (i = o.trys).length > 0 && i[i.length - 1]) &&
                  (6 === a[0] || 2 === a[0])
                ) {
                  o = 0;
                  continue;
                }
                if (3 === a[0] && (!i || (a[1] > i[0] && a[1] < i[3]))) {
                  o.label = a[1];
                  break;
                }
                if (6 === a[0] && o.label < i[1]) {
                  (o.label = i[1]), (i = a);
                  break;
                }
                if (i && o.label < i[2]) {
                  (o.label = i[2]), o.ops.push(a);
                  break;
                }
                i[2] && o.ops.pop(), o.trys.pop();
                continue;
            }
            a = n.call(e, o);
          } catch (e) {
            (a = [6, e]), (r = 0);
          } finally {
            t = i = 0;
          }
        if (5 & a[0]) throw a[1];
        return { value: a[0] ? a[1] : void 0, done: !0 };
      })([a, s]);
    };
  }
}
var Message = (function () {
  function e() {}
  return (
    (e.add = function (n) {
      e._handleList.push(n), window.addEventListener('message', n, !1);
    }),
    (e.remove = function (n) {
      var t = e._handleList.indexOf(n);
      t >= 0 && e._handleList.splice(t, 1),
        window.removeEventListener('message', n, !1);
    }),
    (e.empty = function () {
      for (; e._handleList.length; )
        window.removeEventListener('message', e._handleList.shift(), !1);
    }),
    (e.parse = function (e) {
      return 'object' == typeof e ? e : JSON.parse(e);
    }),
    (e._handleList = []),
    e
  );
})();
function isPlainObject(e) {
  if (!e) return !1;
  for (var n = e; null !== Object.getPrototypeOf(n); )
    n = Object.getPrototypeOf(n);
  return Object.getPrototypeOf(e) === n;
}
var officeTypes,
  officeNameTypes,
  modeTypes,
  _this = this;
!(function (e) {
  (e.unknown = 'unknown'),
    (e.spreadsheet = 's'),
    (e.writer = 'w'),
    (e.presentation = 'p'),
    (e.pdf = 'f');
})(officeTypes || (officeTypes = {})),
  (function (e) {
    (e.wps = 'w'), (e.et = 's'), (e.presentation = 'p'), (e.pdf = 'f');
  })(officeNameTypes || (officeNameTypes = {})),
  (function (e) {
    (e.nomal = 'nomal'), (e.simple = 'simple');
  })(modeTypes || (modeTypes = {}));
var getId = (function (e) {
    return function () {
      return ++e;
    };
  })(0),
  getIframe = (function (e) {
    return function (n, t) {
      if (!e) {
        e = document.createElement('iframe');
        var r = {
          id: 'office-iframe',
          src: n,
          scrolling: 'no',
          frameborder: '0',
          allowfullscreen: 'allowfullscreen',
          webkitallowfullscreen: 'true',
          mozallowfullscreen: 'true',
          className: 'web-office-iframe',
        };
        for (var i in r) e.setAttribute(i, r[i]);
        t ? t.appendChild(e) : document.body.appendChild(e),
          (e.destroy = function () {
            e.parentNode.removeChild(e), (e = null);
          });
      }
      return e;
    };
  })(null),
  sendMsgToWps = function (e) {
    getIframe().contentWindow.postMessage(JSON.stringify(e), '*');
  },
  apiChannelOld = function (e) {
    return new Promise(function (n) {
      var t = getId();
      e.type = getOfficeType();
      var r = function (e) {
        var i = Message.parse(e.data);
        'wps.api.reply' === i.eventName &&
          i.msgId === t &&
          (n(i.data), Message.remove(r));
      };
      Message.add(r),
        sendMsgToWps({ eventName: 'wps.jssdk.api', data: e, msgId: t });
    });
  },
  channelList = [],
  childChannelList = [],
  childMode = !1,
  sending = !1,
  childSending = !1,
  destroyUtils = function () {
    (channelList = []),
      (childChannelList = []),
      (childMode = !1),
      (sending = !1),
      (childSending = !1);
  },
  apiChannel = function (e, n, t) {
    return __awaiter(_this, void 0, void 0, function () {
      var r, i, a, o, s, c, p, d, l, f;
      return __generator(this, function (u) {
        return (
          (r = childMode ? childChannelList : channelList),
          (i = getId()),
          (n.type = getOfficeType()),
          (s = new Promise(function (e, n) {
            (a = e), (o = n);
          })),
          (c = {}),
          n.args &&
            ((p = reduceArgs(n.args)),
            (d = p[0]),
            (l = p[1]),
            (n.args = d),
            (c = l)),
          (f = function () {
            var n = this,
              p = function (s) {
                return __awaiter(n, void 0, void 0, function () {
                  var n, d, l;
                  return __generator(this, function (f) {
                    switch (f.label) {
                      case 0:
                        return 'api.callback' ===
                          (n = Message.parse(s.data)).eventName &&
                          n.callbackId &&
                          c[n.callbackId]
                          ? ((childMode = !0),
                            [4, c[n.callbackId].apply(c, n.data.args)])
                          : [3, 2];
                      case 1:
                        (d = f.sent()),
                          sendMsgToWps({
                            eventName: 'api.callback.reply',
                            result: d,
                            callbackId: n.callbackId,
                          }),
                          (f.label = 2);
                      case 2:
                        if (n.eventName === e + '.reply' && n.msgId === i) {
                          if (n.error) {
                            for (
                              (l = new Error('')).stack = n.error + '\n' + t;
                              r.length;

                            )
                              r.shift();
                            childMode ? (childSending = !1) : (sending = !1),
                              o(l);
                          } else a(n.result);
                          Message.remove(p);
                        }
                        return [2];
                    }
                  });
                });
              };
            return Message.add(p), s;
          }),
          r.push([{ eventName: e, data: n, msgId: i }, f]),
          sendApiChannel(r),
          [2, s]
        );
      });
    });
  };
function reduceArgs(e) {
  var n = {};
  return [
    (e = e.map(function (e) {
      if (isPlainObject(e)) {
        var t = {};
        for (var r in e) {
          var i = e[r];
          if ('function' == typeof i) {
            var a = getId();
            (n[a] = i), (i = { callbackId: a });
          }
          t[r] = i;
        }
        return t;
      }
      if ('function' == typeof e) {
        a = getId();
        return (n[a] = e), { callbackId: a };
      }
      return e;
    })),
    n,
  ];
}
function sendApiChannel(e) {
  return __awaiter(this, void 0, void 0, function () {
    var n, t, r, i;
    return __generator(this, function (a) {
      switch (a.label) {
        case 0:
          if (
            ((n = childMode), (childMode ? childSending : sending) || !e.length)
          )
            return [3, 4];
          childMode ? (childSending = !0) : (sending = !0), (a.label = 1);
        case 1:
          return e.length
            ? ((t = e.shift()),
              (r = t[0]),
              (i = t[1]),
              'function' == typeof (r = __assign({}, r)).data &&
                (r.data = r.data()),
              sendMsgToWps(r),
              [4, i()])
            : [3, 3];
        case 2:
          return a.sent(), [3, 1];
        case 3:
          return (
            childMode ? (childSending = !1) : (sending = !1),
            n && (childMode = !1),
            [2, sendApiChannel(n ? channelList : childChannelList)]
          );
        case 4:
          return [2];
      }
    });
  });
}
function apiChildMode() {
  childMode = !0;
}
var MsoTriState,
  userConfHandler = function (e, n) {
    void 0 === n && (n = !0);
    var t = __assign({}, e),
      r = t.headers,
      i = void 0 === r ? {} : r,
      a = t.subscriptions,
      o = void 0 === a ? {} : a,
      s = t.mode,
      c = void 0 === s ? modeTypes.nomal : s,
      p = i.backBtn,
      d = void 0 === p ? {} : p,
      l = i.shareBtn,
      f = void 0 === l ? {} : l,
      u = i.otherMenuBtn,
      b = void 0 === u ? {} : u,
      g = function (e, t) {
        e.subscribe &&
          'function' == typeof e.subscribe &&
          ((e.callback = t), (o[t] = e.subscribe), n && delete e.subscribe);
      };
    if (
      (g(d, 'wpsconfig_back_btn'),
      g(f, 'wpsconfig_share_btn'),
      g(b, 'wpsconfig_other_menu_btn'),
      b.items && Array.isArray(b.items))
    ) {
      var m = [];
      b.items.forEach(function (e, n) {
        switch ((void 0 === e && (e = {}), e.type)) {
          case 'export_img':
            (e.type = 1), (e.callback = 'export_img');
            break;
          case 'export_pdf':
            (e.type = 1), (e.callback = 'export_pdf');
            break;
          case 'save_version':
            (e.type = 1), (e.callback = 'save_version');
            break;
          case 'about_wps':
            (e.type = 1), (e.callback = 'about_wps');
            break;
          case 'split_line':
            e.type = 2;
            break;
          case 'custom':
            (e.type = 3), g(e, 'wpsconfig_other_menu_btn_' + n), m.push(e);
        }
      }),
        m.length && (isMobile || isInMiniProgram) && (b.items = m);
    }
    if (
      (c === modeTypes.simple &&
        (t.wpsUrl && (t.wpsUrl += '&simple&hidecmb'),
        t.url && (t.url += '&simple&hidecmb')),
      t.debug &&
        (t.wpsUrl && (t.wpsUrl += '&debugger'),
        t.url && (t.url += '&debugger')),
      t.wordOptions && (t.wpsOptions = t.wordOptions),
      t.excelOptions && (t.etOptions = t.excelOptions),
      t.pptOptions && (t.wppOptions = t.pptOptions),
      'object' == typeof o.print)
    ) {
      var v = 'wpsconfig_print';
      'function' == typeof o.print.subscribe &&
        ((o[v] = o.print.subscribe),
        (t.print = { callback: v }),
        void 0 !== o.print.custom && (t.print.custom = o.print.custom)),
        delete o.print;
    }
    'function' == typeof o.exportPdf &&
      ((o[(v = 'wpsconfig_export_pdf')] = o.exportPdf),
      (t.exportPdf = { callback: v }),
      delete o.exportPdf);
    return __assign({}, t, { subscriptions: o });
  },
  getOfficeType = (function (e) {
    return function (n) {
      if ((void 0 === n && (n = ''), !e && n)) {
        var t = n.toLowerCase();
        -1 !== t.indexOf('/office/s/') && (e = officeTypes.spreadsheet),
          -1 !== t.indexOf('/office/w/') && (e = officeTypes.writer),
          -1 !== t.indexOf('/office/p/') && (e = officeTypes.presentation),
          -1 !== t.indexOf('/office/f/') && (e = officeTypes.pdf);
      }
      if (!e) {
        var r = n.match(/[\?&]type=([a-z]+)/) || [];
        e = officeNameTypes[r[1]] || '';
      }
      return e;
    };
  })(''),
  agent = window.navigator.userAgent.toLowerCase(),
  isMobile = /Android|webOS|iPhone|iPod|BlackBerry|iPad/i.test(agent),
  isInMiniProgram = (function () {
    try {
      return (
        -1 !== window._parent.location.search.indexOf('from=wxminiprogram')
      );
    } catch (e) {
      return !1;
    }
  })();
function mitt(e) {
  return (
    (e = e || Object.create(null)),
    {
      on: function (n, t) {
        (e[n] || (e[n] = [])).push(t);
      },
      off: function (n, t) {
        e[n] && e[n].splice(e[n].indexOf(t) >>> 0, 1);
      },
      emit: function (n, t) {
        (e[n] || []).slice().map(function (e) {
          e(t);
        }),
          (e['*'] || []).slice().map(function (e) {
            e(n, t);
          });
      },
    }
  );
}
!(function (e) {
  (e[(e.msoFalse = 0)] = 'msoFalse'), (e[(e.msoTrue = -1)] = 'msoTrue');
})(MsoTriState || (MsoTriState = {}));
var objId = 0,
  collectObjIdHandlers = new Set();
function createObjId(e) {
  return ++objId, !e && collectObjId(objId), objId;
}
function collectObjId(e) {
  collectObjIdHandlers.forEach(function (n) {
    return n(e);
  });
}
function makeCollectObjIdHandle(e) {
  return function () {
    var n = [],
      t = function (e) {
        n.push(e);
      };
    return (
      collectObjIdHandlers.add(t),
      {
        End: function () {
          e(n), collectObjIdHandlers.delete(t);
        },
      }
    );
  };
}
function destroyApplication() {
  collectObjIdHandlers = new Set();
}
function initApplication(e, n) {
  var t = this,
    r = n.Events,
    i = n.Enum,
    a = n.Props,
    o = a[0],
    s = a[1],
    c = { objId: objId };
  switch (
    (assign(c, o, s),
    (c.Events = r),
    (c.Enum = i),
    (e.Enum = c.Enum),
    (e.Events = c.Events),
    getOfficeType(e.url))
  ) {
    case officeTypes.writer:
      e.WordApplication = e.WpsApplication = function () {
        return c;
      };
      break;
    case officeTypes.spreadsheet:
      e.ExcelApplication = e.EtApplication = function () {
        return c;
      };
      break;
    case officeTypes.presentation:
      e.PPTApplication = e.WppApplication = function () {
        return c;
      };
      break;
    case officeTypes.pdf:
      e.PDFApplication = function () {
        return c;
      };
  }
  (e.Application = c),
    (e.Free = function (e) {
      return apiChannel('api.free', { objId: e }, '');
    }),
    (e.Stack = c.Stack = makeCollectObjIdHandle(function (n) {
      return e.Free(n);
    }));
  var p = {};
  Message.add(function (e) {
    return __awaiter(t, void 0, void 0, function () {
      var n, t, r, i, a;
      return __generator(this, function (o) {
        return (
          'api.event' === (n = Message.parse(e.data)).eventName &&
            n.data &&
            ((t = n.data),
            (r = t.eventName),
            (i = t.data),
            t.objIds,
            (a = p[r]) && (apiChildMode(), a(i))),
          [2]
        );
      });
    });
  }),
    (c.Sub = {}),
    Object.values(r).forEach(function (e) {
      Object.defineProperty(c.Sub, e, {
        set: function (n) {
          (p[e] = n),
            sendMsgToWps({
              eventName: 'api.event.register',
              data: { eventName: e, register: !!n, objId: ++objId },
            });
        },
      });
    });
}
var wps,
  polyfillApi = [
    'ExportAsFixedFormat',
    'GetOperatorsInfo',
    'ImportDataIntoFields',
    'ReplaceText',
    'ReplaceBookmark',
    'GetBookmarkText',
    'GetComments',
  ];
function assign(e, n, t) {
  n = n.slice(0);
  for (
    var r = function () {
      var r = n.shift();
      !r.alias &&
        ~polyfillApi.indexOf(r.prop) &&
        n.push(__assign({}, r, { alias: r.prop + 'Async' })),
        Object.defineProperty(e, r.alias || r.prop, {
          get: function () {
            var n = 1 === r.cache,
              i = n && this['__' + r.prop + 'CacheValue'];
            if (i) return i;
            var a = new Error('').stack.split('\n').slice(2).join('\n'),
              o = createObjId(n),
              s = function () {
                for (var n, i = [], o = 0; o < arguments.length; o++)
                  i[o] = arguments[o];
                return (
                  void 0 !== r.caller
                    ? assign((n = { objId: createObjId() }), t[r.caller], t)
                    : (n = {}),
                  wrapper(
                    n,
                    'api.caller',
                    function () {
                      return {
                        obj: s,
                        parentObjId: e.objId,
                        objId: n.objId || -1,
                        args: i,
                        prop: r.prop,
                      };
                    },
                    a
                  ),
                  n
                );
              };
            return (
              (s.objId = -1),
              void 0 !== r.getter && ((s.objId = o), assign(s, t[r.getter], t)),
              wrapper(
                s,
                'api.getter',
                function () {
                  return { parentObjId: e.objId, objId: s.objId, prop: r.prop };
                },
                a
              ),
              n && (this['__' + r.prop + 'CacheValue'] = s),
              s
            );
          },
          set: function (n) {
            wrapper(
              {},
              'api.setter',
              function () {
                return {
                  parentObjId: e.objId,
                  objId: -1,
                  prop: r.prop,
                  value: n,
                };
              },
              new Error('').stack.split('\n').slice(2).join('\n')
            );
          },
        });
    };
    n.length;

  )
    r();
}
function wrapper(e, n, t, r) {
  var i = apiChannel(n, t, r).then(function (n) {
    return n && n.objId ? ((e.then = void 0), (e.objId = n.objId), e) : n;
  });
  (e.then = function (e, n) {
    return i.then(e, n);
  }),
    (e.Destroy = function () {
      return apiChannel('api.free', { objId: e.objId }, '');
    });
}
var EventTypes = { fileOpen: 'fileOpen' },
  isAdvanceApiReady = function (e) {
    return 'api.ready' === e;
  },
  Listener = function (e, n) {
    void 0 === e && (e = {});
    Message.add(function (t) {
      var r = Message.parse(t.data),
        i = r.eventName,
        a = void 0 === i ? '' : i,
        o = r.data,
        s = void 0 === o ? null : o,
        c = r.url,
        p = void 0 === c ? null : c;
      -1 === ['wps.jssdk.api'].indexOf(a) &&
        ('ready' === a
          ? (sendMsgToWps({ eventName: 'setConfig', data: e }),
            wps.tokenData &&
              sendMsgToWps({ eventName: 'setToken', data: wps.tokenData }),
            wps.commandBars &&
              sendMsgToWps({
                eventName: 'setCommandBars',
                data: wps.commandBars,
              }),
            (wps.iframeReady = !0))
          : 'open.result' === a
          ? wps.emit(EventTypes.fileOpen, s)
          : 'api.ready' === a && initApplication(wps, s),
        'function' == typeof n[a] && n[a](wps, p || s));
    });
  };
function config(e) {
  void 0 === e && (e = {}), wps && wps.destroy();
  try {
    var n,
      t = userConfHandler(e),
      r = t.wpsUrl,
      i = t.subscriptions,
      a = void 0 === i ? {} : i,
      o = t.mount,
      s = void 0 === o ? null : o,
      c = t.url,
      p = r || c,
      d = getIframe(p, s);
    return (
      delete t.mount,
      r && delete t.wpsUrl,
      c && delete t.url,
      delete t.subscriptions,
      (wps = {
        url: p,
        version: '1.1.0',
        iframe: d,
        Enum: __assign({}, MsoTriState),
        iframeReady: !1,
        tokenData: null,
        commandBars: null,
        setToken: function (e) {
          (wps.tokenData = e),
            wps.iframeReady && sendMsgToWps({ eventName: 'setToken', data: e });
        },
        ready: function () {
          return (
            n ||
            (n = new Promise(function (e) {
              var n = function (t) {
                var r = Message.parse(t.data).eventName;
                isAdvanceApiReady(r) && (e(), Message.remove(n));
              };
              Message.add(n);
            }))
          );
        },
        destroy: function () {
          d.destroy(),
            Message.empty(),
            (wps = null),
            destroyUtils(),
            destroyApplication();
        },
        save: function () {
          return apiChannelOld({ api: 'save' });
        },
        setCommandBars: function (e) {
          (wps.commandBars = e),
            wps.iframeReady &&
              sendMsgToWps({ eventName: 'setCommandBars', data: e });
        },
        updateConfig: function (e) {
          void 0 === e && (e = {});
          var n = userConfHandler(e, !1),
            t = n.subscriptions,
            r = void 0 === t ? {} : t;
          Message.empty(),
            Listener(n, r),
            n && sendMsgToWps({ eventName: 'setConfig', data: n });
        },
      }),
      (wps = __assign({}, wps, new mitt.prototype.constructor())),
      Listener(t, a),
      wps.ready(),
      wps
    );
  } catch (e) {
    console.error(e);
  }
}
console.log('WebOfficeSDK JS-SDK V1.1.0');
var wps$1 = Object.freeze({ Listener: Listener, config: config });
window.WPS = wps$1;
var config$1 = config,
  index = { config: config$1 };
(exports.config = config$1), (exports.default = index);
